package com.tgy.algorithm.base;

public class _奇偶数 {

    public static void printNumBit(long num, int bit) {
        for (int i = bit - 1; i >= 0; i--) {
            System.out.print((num & (1 << i)) == 0 ?"0":"1");
        }
        System.out.println();
    }

    /*
     * 一个数组里面有多个数，已知有一种是出现了奇数次，其他都是偶数次，求这个数。
     * 这里用到了异或运算规则的交换律，
     * A^B^C = A^C^B = B^C^A = B^A^C =  C^A^B = C^B^A
     *
     * A^0 = A
     * A^A = 0
     */
    public static int findOddNum(int[] arr) {
        int oddNum = 0;
        for (int i:arr) {
            oddNum ^= i;
        }
        return oddNum;
    }

    public static void swap() {
        int one = 100;
        int two = 200;
        System.out.println(one +  " " + two);
//      这里能进行交互，one和 two必须是两个内存值，不能在一个内存里面进行操作，因为在一个内存里面进行操作，后面会覆盖前面的
        one = one ^ two;
        two = one ^ two;  // one ^ two ^ two
        one = one ^ two;  // one ^ two ^ two * two
        System.out.println(one +  " " + two);
        int[] nums = new int[]{1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20};
        // 这里变成了0，后面都是0
        nums[1] = nums[1] ^ nums[1];
    }

    // 取出最右边的1
    public static int getLastRightOne(int num) {

        // 1011
        // 0100 => 0101
        // 0001000    0001000
        // 1110111 => 1111000
        return num & ((~num) + 1);
    }

    public static void main(String[] args) {

//        int val = findOddNum(new int[]{1,1,2,2,3,3,3,4,4,5,5});
//        System.out.println(val);
//        swap();
        int num = 440;
//        printNumBit(num, Integer.SIZE);
//        int result = getLastRightOne(440);
//        printNumBit(result, Integer.SIZE);

        int num01 = (~num) + 1;
        System.out.println(num + " " + num01);
        printNumBit(num, Integer.SIZE);

        printNumBit(num01, Integer.SIZE);
    }
}
